package com.aaa.controller.system;

import com.aaa.controller.BaseController;
import com.aaa.entity.Result;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @author ：肖成杰（1752167034@qq.com）
 * @date ：Created in 2022/8/27 9:13
 * @description：文件上传
 * @modified By：
 * @version: 1.0
 */
@Controller
//@RequestMapping("file")
public class FileController extends BaseController {
    @ResponseBody
    @RequestMapping("upload.do")
    public Result FileUpload(MultipartFile file){
        //获取原始文件名
        String filename = file.getOriginalFilename();
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
//        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        String endpoint = "oss-cn-hangzhou.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tMuu1Lyc8kPcdrfKzwJ";
        String accessKeySecret = "k0Mvlw0i5tOKWvJ8csPd4PXqGdGaWD";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "xj-xcj";
        String objectName = "img/"+ UUID.randomUUID() + filename;

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(file.getBytes()));
            String url ="https://"+bucketName+"."+endpoint+"/"+objectName;
            return success(url);
        } catch (IOException e) {
            return fail();
        }finally {
            ossClient.shutdown();
        }

    }
}